var express =require('express')
var bodyParser = require('body-parser');
var app=express()
app.use(express.static(__dirname));
app.use(bodyParser.json());
var Bmob=require('./lib/app');

Bmob.initialize("643d41ccb3b1eede8a2a63988e90a6a7", "a65c34186f9f3385c75dd76a02fd022b");
// //设置跨域访问
// app.all('*', function(req, res, next) {
//   res.header("Access-Control-Allow-Origin", "*");
// //   res.header("Access-Control-Allow-Headers", "X-Requested-With");
// //   res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
// //   res.header("X-Powered-By",' 3.2.1');
// //   res.header("Content-Type", "application/json;charset=utf-8");
// //   next();
// // });

app.post('/register',(req,res)=>{
    let emailRule=/\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/;
    let passwordRule=/^[\s\S]*.*[^\s][\s\S]*$/;
      if(!emailRule.test(req.query.email)){
          res.json({error:'电子邮箱格式有误'})
        }
      if(!passwordRule.test(req.query.password)){
         res.json({error:'密码不能为空'})
      }

    let params = {
        username:req.query.email,
        email:req.query.email,
        password:req.query.password
    }
      Bmob.User.register(params).then(data => {
        res.status(200)
        res.json(data)
      }).catch(err => {
        res.json(err)
      });

});

app.post('/login',(req,res)=>{
  let emailRule=/\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/;
  let passwordRule=/^[\s\S]*.*[^\s][\s\S]*$/;
  if(!emailRule.test(req.query.email)){
    res.json({error:'电子邮箱格式有误'})
  }
  if(!passwordRule.test(req.query.password)){
    res.json({error:'密码不能为空'})
  }
  Bmob.User.login(req.query.email,req.query.password).then(data => {
    res.json(data)
  }).catch(err => {
    res.json(err)
  });
})

app.listen(3000,()=>{
  console.log('connecting')
})

